package org.zhtkj.web.scheduler;

import java.util.List;
import java.util.Set;

import org.joda.time.DateTime;
import org.joda.time.Minutes;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.zhtkj.framework.session.SessionManager;
import org.zhtkj.web.dao.RuntimeInfoMapper;
import org.zhtkj.web.model.RuntimeInfo;
import org.zhtkj.web.utils.MediaPacketUtils;
import org.zhtkj.web.utils.MediaPacketUtils.ActionInfo;
import org.zhtkj.web.utils.MediaPacketUtils.PacketInfo;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

/**
 * ClassName: WebScheduler 
 * @Description: 定时任务
 * @author Nikotesla
 * @date 2019年1月25日
 */
 
@Component
public class WebScheduler {

    @Autowired
    private SessionManager sessionManager;
    
    @Autowired
    private RuntimeInfoMapper runtimeInfoMapper;
    
	/**
	 * @Description: 移除不活跃的session   
	 */
	@Scheduled(cron = "0 3/3 * * * ?")
	public void clearSession() {
		sessionManager.clearSession();
	}
	
	/**
	 * @Description: 更新实时信息表车辆在线状态   
	 * @return void  
	 * @throws
	 * @author Nikotesla
	 * @date 2019年1月29日
	 */
	@Scheduled(cron = "0 6/6 * * * ?")
	public void updateRuntimeInfo() {
		List<RuntimeInfo> runtimeInfos = runtimeInfoMapper.selectList(new QueryWrapper<RuntimeInfo>());
		DateTime now = DateTime.now();
		for (RuntimeInfo runtimeInfo: runtimeInfos) {
			if (runtimeInfo.getOnlineStatus() == 1 && Minutes.minutesBetween(new DateTime(runtimeInfo.getUpdateTime()), now).getMinutes() > 6) {
				RuntimeInfo update = new RuntimeInfo();
				update.setLicensePlate(runtimeInfo.getLicensePlate());
				update.setOnlineStatus(0);
				update.setOfflineTime(runtimeInfo.getUpdateTime());
				runtimeInfoMapper.updateById(update);
			}
		}
	}
	
	/**
	 * @Description: 定时删除MediaPacketUtils里面的过期的包   
	 * @return void  
	 */
	@Scheduled(cron = "0 10/10 * * * ?")
	public void clearMediaPacketData() {
		DateTime now = DateTime.now();
		//移除过期的packet数据
		Set<String> packetKeys = MediaPacketUtils.packetMap.keySet();
		for (String key: packetKeys) {
			PacketInfo packetInfo = MediaPacketUtils.getPacket(key);
			if (packetInfo != null) {
				if (Minutes.minutesBetween(packetInfo.getReceiveTime(), now).getMinutes() > 10) {
					MediaPacketUtils.packetMap.remove(key);
				}
			}
		}
		//移除过期的action数据
		Set<String> actionKeys = MediaPacketUtils.packetMap.keySet();
		for (String key: actionKeys) {
			ActionInfo actionInfo = MediaPacketUtils.getAction(key);
			if (actionInfo != null) {
				if (Minutes.minutesBetween(actionInfo.getReceiveTime(), now).getMinutes() > 10) {
					MediaPacketUtils.actionMap.remove(key);
				}
			}
		}
	}
	
}
